package com.example.myapplication;

import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 创建者：YangLei
 * 时间：2016/5/30
 * 作用说明：长途网络测试
 * 使用说明：
 */
public class ChangTuNetTestActivity extends Activity {

    private final String LIANTONG_URL = "http://182.118.29.97/v1/556d22d1/ca37406e.st3?t=22076980";
    private final String DIANXIN_URL = "http://218.30.117.150/v1/0c69b881/7a574459.st3?t=22085030";
    private final String TIETONG_URL = "http://122.70.131.238/v1/dd532511/a9ac948c.st3?t=22093142";

    private TextView tv_type, tv_now_speed, tv_ave_speed;
    private Button btn;
    private ImageView needle;
    private Info info;
    private boolean flag;
    private int last_degree = 0, cur_degree;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 0x123) {
                tv_now_speed.setText(msg.arg1 + "KB/S");
                tv_ave_speed.setText(msg.arg2 + "KB/S");
                startAnimation(msg.arg1);
            } else if (msg.what == 0x100) {//联通测速完成
                tv_now_speed.setText("0KB/S");
                String result = tv_ave_speed.getText().toString();
                liantongTv.setText(result);
                startAnimation(0);
                startTest(DIANXIN_URL);
            } else if (msg.what == 0x101) {//电信测速完成
                tv_now_speed.setText("0KB/S");
                String result = tv_ave_speed.getText().toString();
                dianxinTv.setText(result);
                startAnimation(0);
                startTest(TIETONG_URL);
            } else if (msg.what == 0x102) {//移动测速完成
                tv_now_speed.setText("0KB/S");
                String result = tv_ave_speed.getText().toString();
                tietongTv.setText(result);
                startAnimation(0);
                btn.setText("开始测试");
                btn.setEnabled(true);
            }
            return false;
        }
    });

    private TextView liantongTv, dianxinTv, tietongTv;
    private TextView currentNetTypeTv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.changtu_test_activity);
        liantongTv = (TextView) findViewById(R.id.liantong_speed_tv);
        dianxinTv = (TextView) findViewById(R.id.dianxin_speed_tv);
        tietongTv = (TextView) findViewById(R.id.tietong_speed_tv);
        info = new Info();

        Button backButton = (Button) findViewById(R.id.back_button);
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        tv_type = (TextView) findViewById(R.id.connection_type);
        currentNetTypeTv = (TextView) findViewById(R.id.current_nettype_tv);
        tv_now_speed = (TextView) findViewById(R.id.now_speed);
        tv_ave_speed = (TextView) findViewById(R.id.ave_speed);
        needle = (ImageView) findViewById(R.id.needle);
        btn = (Button) findViewById(R.id.start_btn);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                startTest(LIANTONG_URL);
            }
        });

        new AsyncTask<String, Integer, String>() {

            @Override
            protected String doInBackground(String... params) {
                return GetNetIp();
            }

            @Override
            protected void onPostExecute(String s) {
                if (s != null && !"".equals(s))
                    currentNetTypeTv.setText(s.substring(s.indexOf("(") + 1, s.length() - 1));
                super.onPostExecute(s);
            }
        }.execute();
    }

    private void startTest(String url_String) {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        tv_type.setText(networkInfo.getTypeName());
        flag = true;
        btn.setText("测试中");
        btn.setEnabled(false);
        info.hadfinishByte = 0;
        info.speed = 0;
        info.totalByte = 1024;
        new DownloadThread(url_String).start();
        new GetInfoThread(url_String).start();
    }

    public static String GetNetIp() {
        String IP;
        try {
            String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
            URL url = new URL(address);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setUseCaches(false);

            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream in = connection.getInputStream();

                // 将流转化为字符串
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(in));

                String tmpString;
                StringBuilder retJSON = new StringBuilder();
                while ((tmpString = reader.readLine()) != null) {
                    retJSON.append(tmpString + "\n");
                }

                JSONObject jsonObject = new JSONObject(retJSON.toString());
                String code = jsonObject.getString("code");
                if (code.equals("0")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    IP = data.getString("ip") + "("
//                            + data.getString("country")
//                            + data.getString("area") + "区"
                            + data.getString("region") + data.getString("city")
                            + data.getString("isp") + ")";

                    Log.e("提示", "您的IP地址是：" + IP);
                } else {
                    IP = "";
                    Log.e("提示", "IP接口异常，无法获取IP地址！");
                }
            } else {
                IP = "";
                Log.e("提示", "网络连接异常，无法获取IP地址！");
            }
        } catch (Exception e) {
            IP = "";
            Log.e("提示", "获取IP地址时出现异常，异常信息是：" + e.toString());
        }
        return IP;
    }

    private int max_second = 8;

    class DownloadThread extends Thread {
        private String url_string;

        public DownloadThread(String url_string) {
            this.url_string = url_string;
        }

        @Override
        public void run() {
            long start_time, cur_time;
            URL url;
            URLConnection connection;
            InputStream iStream;
            try {
                url = new URL(url_string);
                connection = url.openConnection();
                info.totalByte = connection.getContentLength();
                iStream = connection.getInputStream();
                start_time = System.currentTimeMillis();
                while (iStream.read() != -1 && flag) {
                    info.hadfinishByte++;
                    cur_time = System.currentTimeMillis();
                    if (cur_time - start_time == 0) {
                        info.speed = 1000;
                    } else {
                        info.speed = info.hadfinishByte * 1000 / (cur_time - start_time);
                    }
                }
                iStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    class GetInfoThread extends Thread {
        private String url;

        public GetInfoThread(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            double sum, counter;
//            int cur_speed;
            int ave_speed;
            try {
                sum = 0;
                counter = 0;
                while (info.hadfinishByte < info.totalByte && flag) {
                    Thread.sleep(1000);
                    sum += info.speed;
                    counter++;
//                    cur_speed = (int) info.speed;
                    ave_speed = (int) (sum / counter);
                    Message msg = new Message();
                    msg.arg1 = ((int) info.speed / 1024);
                    msg.arg2 = ave_speed / 1024;
                    msg.what = 0x123;
                    handler.sendMessage(msg);
                    if (counter >= max_second) {
                        flag = false;
                        if (LIANTONG_URL.equals(url)) {
                            handler.sendEmptyMessage(0x100);
                        } else if (DIANXIN_URL.equals(url)) {
                            handler.sendEmptyMessage(0x101);
                        } else if (TIETONG_URL.equals(url)) {
                            handler.sendEmptyMessage(0x102);
                        }
                    }
                }
                if (info.hadfinishByte == info.totalByte && flag) {
                    if (LIANTONG_URL.equals(url)) {
                        handler.sendEmptyMessage(0x100);
                    } else if (DIANXIN_URL.equals(url)) {
                        handler.sendEmptyMessage(0x101);
                    } else if (TIETONG_URL.equals(url)) {
                        handler.sendEmptyMessage(0x102);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onStop() {
        flag = false;
        super.onStop();
    }

    @Override
    protected void onResume() {
        flag = true;
        super.onResume();
    }

    private void startAnimation(int cur_speed) {
        cur_degree = getDegree(cur_speed);
        RotateAnimation rotateAnimation = new RotateAnimation(last_degree, cur_degree, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setFillAfter(true);
        rotateAnimation.setDuration(1000);
        last_degree = cur_degree;
        needle.startAnimation(rotateAnimation);
    }

    private int getDegree(double cur_speed) {
        int ret;
        if (cur_speed >= 0 && cur_speed <= 512) {
            ret = (int) (15.0 * cur_speed / 128.0);
        } else if (cur_speed >= 512 && cur_speed <= 1024) {
            ret = (int) (60 + 15.0 * (cur_speed - 512) / 256.0);
        } else if (cur_speed >= 1024 && cur_speed <= 5 * 1024) {
            ret = (int) (90 + 15.0 * (cur_speed - 1024) / 1024.0);
        } else if (cur_speed >= 5 * 1024 && cur_speed <= 10 * 1024) {
            ret = (int) (150 + 15.0 * (cur_speed - 5 * 1024) / 2.5 * 1024.0);
        } else {
            ret = 180;
        }
        return ret;
    }
}
